<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { userLogin } from "@/api/login";
import { showSuccessToast, showFailToast } from "vant";
import { useUserStore } from "@/stores/user";

const useStore = useUserStore();
const router = useRouter();

// 账号密码数据
const username = ref("");
const password = ref("");
const knowOne = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
const knowTwo = /^[\w-]{4,16}$/
// 提交事件
function onSubmit() {
  if (!knowOne.test(username.value) || !knowTwo.test(password.value)) {
    return showFailToast('账号密码格式错误');
  }
  userLogin({ tel: username.value, password: password.value }).then((res) => {
    // console.log(res)
    if (res.data.code !== "200") {
      return showFailToast(res.data.message);
    }

    showSuccessToast(res.data.message);
    window.localStorage.setItem("userState", "true");
    // window.localStorage.setItem('userid',res.data.data.userid)
    window.localStorage.setItem("username", username.value);
    // useStore.setUserState(true)
    useStore.userState = true;
    useStore.username = username.value;
    router.push("/");
  });
}

// 注册按钮事件
function setIn() {
  router.push("/register/step1");
}

// 导航栏返回事件
function onClickLeft() {
  router.push("/");
}
</script>

<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="" left-text="返回" left-arrow @click-left="onClickLeft" />

    <!-- 账号密码 -->
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="username" name="用户名" label="用户名" placeholder="手机号号码"
          :rules="[{ required: true, message: '请填写手机号号码' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round type="success" block native-type="submit">
          登录
        </van-button>
        <van-button class="btn2" round block type="primary" native-type="submit" @click="setIn">
          注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.van-nav-bar {
  background-color: #f7fdff;
}

.van-form {
  margin-top: 20%;
}

.btn2 {
  margin-top: 15px;
}
</style>
